﻿using System.Data;
using Oracle.DataAccess.Client;

namespace UwaySoft.EsheetServer.DataLayer.Oracle
{
    public class OracleHelper : SqlHelper<OracleParameter>
    {
        public OracleHelper(string connectionString) : base(connectionString)
        {
        }

        protected override int ExecuteNonQuery(string commandText, params OracleParameter[] parameters)
        {
            using(var conn = new OracleConnection(ConnectionString))
            {
                conn.Open();
                using(var command = new OracleCommand(commandText, conn))
                {
                    if (parameters.Length > 0)
                        command.Parameters.AddRange(parameters);
                    return command.ExecuteNonQuery();
                }
            }
        }

        protected override object ExecuteScalar(string commandText, params OracleParameter[] parameters)
        {
            using (var conn = new OracleConnection(ConnectionString))
            {
                conn.Open();
                using (var command = new OracleCommand(commandText, conn))
                {
                    if (parameters.Length > 0)
                        command.Parameters.AddRange(parameters);
                    return command.ExecuteScalar();
                }
            }
        }

        protected override IRecordReader ExecuteReader(string commandText, params OracleParameter[] parameters)
        {
            var conn = new OracleConnection(ConnectionString);
            var cmd = new OracleCommand(commandText, conn);
            if (parameters.Length > 0)
                cmd.Parameters.AddRange(parameters);
            conn.Open();
            return new OracleRecordHelper(cmd.ExecuteReader());
        }

        protected override DataSet ExecuteDateSet(string commandText, params OracleParameter[] parameters)
        {
            var dataSet = new DataSet();
            using(var conn = new OracleConnection(ConnectionString))
            {
                conn.Open();
                using (var cmd = new OracleCommand(commandText, conn))
                {
                    if (parameters.Length > 0)
                        cmd.Parameters.AddRange(parameters);
                    
                    var orclAdapter = new OracleDataAdapter(cmd);
                    orclAdapter.Fill(dataSet);
                    return dataSet;
                }
            }
        }

        public override IParameter CreateParameter(string name, object value)
        {
            return new OracleParameterHelper(name, value);
        }
    }
}
